package com.anne.fish.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.anne.fish.service.ArticleManager;
import com.anne.fish.model.Article;
import com.anne.fish.webapp.action.BaseAction;

import java.util.List;

public class ArticleAction extends BaseAction implements Preparable {
    private ArticleManager articleManager;
    private List articles;
    private Article article;
    private Long id;
    private String query;

    public void setArticleManager(ArticleManager articleManager) {
        this.articleManager = articleManager;
    }

    public List getArticles() {
        return articles;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String articleId = getRequest().getParameter("article.id");
            if (articleId != null && !articleId.equals("")) {
                article = articleManager.get(new Long(articleId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        articles = articleManager.search(query, Article.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Article getArticle() {
        return article;
    }

    public void setArticle(Article article) {
        this.article = article;
    }

    public String delete() {
        articleManager.remove(article.getId());
        saveMessage(getText("article.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            article = articleManager.get(id);
        } else {
            article = new Article();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (article.getId() == null);

        articleManager.save(article);

        String key = (isNew) ? "article.added" : "article.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}